package top.dark.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import top.dark.common.to.SkuReductionTo;
import top.dark.common.to.SpuBoundTo;
import top.dark.common.utils.PageUtils;
import top.dark.common.utils.Query;
import top.dark.common.utils.R;
import top.dark.product.dao.SpuInfoDao;
import top.dark.product.entity.*;
import top.dark.product.feign.CouponFeignService;
import top.dark.product.feign.SearchFeignService;
import top.dark.product.feign.WareFeignService;
import top.dark.product.service.*;
import top.dark.product.vo.*;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private SearchFeignService searchFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void spuInfoSave(SpuSaveVo spuSaveVo) {
        // 1、spu基本信息  pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
        Long spuId = spuInfoEntity.getId();

        // 2、描述图片信息 pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveDecript(spuInfoDescEntity);

        // 3、图片集信息 pms_spu_images
        List<String> spuImages = spuSaveVo.getImages();
        spuImagesService.saveImages(spuId, spuImages);

        // 4、规格参数信息 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(item.getAttrId());
            AttrEntity attr = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attr.getAttrName());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setSpuId(spuId);
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);


        // 5、sku信息
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item->{
                // 5.1、sku基本信息 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSaleCount(0L);
                List<Images> images = item.getImages();
                String defaultImg = "";
                for (Images img : images) {
                    if (img.getDefaultImg() == 1) {
                        defaultImg = img.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();

                // 5.2、sku图片信息 pms_sku_images
                List<SkuImagesEntity> skuImagesEntities = images.stream()
                        .filter(img -> StringUtils.isNotEmpty(img.getImgUrl())).map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                // 5.3、sku销售属性 pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);

                // 5.4、sku优惠满减信息 gulimall_sms ——> sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                R r = couponFeignService.saveSkuReduction(skuReductionTo);
                if (r.getCode() != 0) {
                    log.error("远程保存sku优惠信息失败");
                }
            });
        }

        // 6、spu的积分信息 gulimall_sms ——> sms_spu_bounds
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(spuSaveVo.getBounds(), spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.save(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCatelogId(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper();
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and((item) -> {
                item.eq("id", key).or().like("spu_name", key);
            });
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public void spuInfoUp(Long spuId) {
        // TODO 1、根据spuId查询出sku信息
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        // TODO 4、根据spuId查询出基础属性
        List<SkuInfoUpEsVo.Attrs> attrs = productAttrValueService.getAttrsBysSpuIdAndSearchType(spuId);

        // TODO 5、远程调用获取库存信息，该sku是否还有库存，hasStock = sum(stock) - locked
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> hasStockMap = null;
        try {
            R<List<SkuStockVo>> r = wareFeignService.skuHasStock(skuIds);
            if (r != null && r.getCode() == 0) {
                // hasStockMap = r.getData().stream().collect(Collectors.toMap(k -> k.getSkuId(), v -> v.getHasStock()));
                List<SkuStockVo> data = r.getData(new TypeReference<List<SkuStockVo>>() {
                });
                if (data != null && data.size() > 0) {
                    hasStockMap = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                }
            }
        } catch (Exception e) {
            log.error("远程调用获取库存信息产生异常，异常信息：{}", e);
        }

        Map<Long, Boolean> finalHasStockMap = hasStockMap;
        List<SkuInfoUpEsVo> skuInfoUpEsVos = skuInfoEntities.stream().map(item -> {
           // TODO 配置sku等基本信息
            SkuInfoUpEsVo vo = new SkuInfoUpEsVo();
            BeanUtils.copyProperties(item, vo);
            vo.setSkuPrice(item.getPrice());
            vo.setSkuImg(item.getSkuDefaultImg());

            // TODO 2、关联的品牌信息
            BrandEntity brand = brandService.getById(item.getBrandId());
            vo.setBrandId(brand.getBrandId());
            vo.setBrandName(brand.getName());
            vo.setBrandImg(brand.getLogo());

            // TODO 3、关联的分类信息
            CategoryEntity category = categoryService.getById(item.getCatalogId());
            vo.setCatalogId(category.getCatId());
            vo.setCatalogName(category.getName());

            vo.setAttrs(attrs);
            if (finalHasStockMap != null) {
                vo.setHasStock(finalHasStockMap.get(vo.getSkuId()));
            } else {
                vo.setHasStock(true);
            }

            // TODO 6、热点信息，暂时置为0
            vo.setHotScore(0L);
            return vo;
        }).collect(Collectors.toList());

        // TODO 7、远程调用search服务，将组合数据存储到ES中
        R r = searchFeignService.spuInfoUp(skuInfoUpEsVos);
        if (r != null && r.getCode() == 0) {
            // TODO 8、上面所有的数据更新完毕，更新商品的状态
            baseMapper.updatePublishStatus(spuId);
        }
    }

}